const Region = require("../../model/region.model");
const Sequelize = require("sequelize");
function buildTree(areas) {
  const rootAreas = areas.filter((area) => area.pid === 0);

  const tree = rootAreas.map((rootArea) => ({
    id: rootArea.id,
    title: rootArea.title,
    children: buildChildren(areas, rootArea.id),
  }));

  return tree;
}

// function buildChildren(areas, parentId) {
//   return areas
//     .filter((area) => area.pid === parentId)
//     .map((area) => ({
//       id: area.id,
//       title: area.title,
//       children: buildChildren(areas, area.id),
//     }));
// }
function buildChildren(areas, parentId) {
  const children = areas.filter((area) => area.pid === parentId);
  return children.map((area) => {
    if (areas.some((child) => child.pid === area.id)) {
      return {
        id: area.id,
        title: area.title,
        children: buildChildren(areas, area.id),
      };
    } else {
      return {
        id: area.id,
        title: area.title,
      };
    }
  });
}
class RegionService {
  async getRegion(args) {
    const { rows: list, count: total } = await Region.findAndCountAll({});
    const treeData = buildTree(list);
    return {
      total,
      treeData,
    };
  }
}

module.exports = new RegionService();
